import { createRouter, createWebHistory, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import App from '@/App.vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { loading } from '@/utils/loading'
import useUserStore from '@/stores/modules/user'
import { PageEnum } from '@/enums/pageEnum'
import { clearAuthInfo } from '@/utils/auth'
import { MenuEnum } from '@/enums/appEnums'
import { isExternal } from '@/utils/validate'
// 过滤路由所需要的数据
export function filterAsyncRoutes(routes: any[], firstRoute = true) {
  return routes.map((route) => {
    const routeRecord = createRouteRecord(route, firstRoute)
    if (route.children != null && route.children && route.children.length) {
      routeRecord.children = filterAsyncRoutes(route.children, false)
    }
    return routeRecord
  })
}
// 创建一条路由记录
export function createRouteRecord(route: any, firstRoute: boolean): RouteRecordRaw {
  //@ts-ignore
  const routeRecord: RouteRecordRaw = {
    path: isExternal(route.paths) ? route.paths : firstRoute ? `/${route.paths}` : route.paths,
    name: Symbol(route.paths),
    meta: {
      hidden: !route.isShow,
      keepAlive: !!route.isCache,
      title: route.menuName,
      perms: route.perms,
      query: route.params,
      icon: route.menuIcon,
      type: route.menuType,
      activeMenu: route.selected
    }
  }
  switch (route.menuType) {
    case MenuEnum.CATALOGUE:
      routeRecord.component = firstRoute ? LAYOUT : RouterView
      if (!route.children) {
        routeRecord.component = RouterView
      }
      break
    case MenuEnum.MENU:
      routeRecord.component = loadRouteView(route.component)
      break
  }
  return routeRecord
}

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'App',
    redirect: '/home',
    component: App,
    children: []
  },
  {
    // 前台
    path: '/home',
    name: 'Home',
    redirect: '/home',
    meta: { title: '首页' },
    component: () => import('@/views/Layout/Index.vue'),
    children: [
      {
        path: '',
        name: 'HomePage',
        meta: { title: '首页' },
        component: () => import('@/views/Home/Index.vue')
      },
      {
        path: 'logo',
        name: 'Home',
        meta: { title: '首页' },
        component: () => import('@/views/Home/Index.vue')
      },
      {
        path: 'sketch',
        name: 'Sketch',
        meta: { title: '效果图' },
        redirect: '/home/sketch',
        children: [
          {
            path: '',
            name: 'SketchIndex',
            meta: { title: '效果图' },
            component: () => import('@/views/Sketch/Index.vue')
          },
          {
            path: 'pic/:id',
            name: 'pic',
            meta: { title: '照片' },
            component: () => import('@/views/Sketch/Pic.vue')
          }
        ]
      },
      {
        path: 'strategy',
        name: 'Strategy',
        meta: { title: '装修攻略' },
        component: () => import('@/views/Strategy/Index.vue')
      },
      {
        path: 'service',
        name: 'Service',
        meta: { title: '保障服务' },
        component: () => import('@/views/Service/Index.vue')
      },
      {
        path: 'about',
        name: 'About',
        meta: { title: '关于我们' },
        component: () => import('@/views/About/Index.vue')
      },
      {
        path: 'more',
        name: 'More',
        meta: { title: '更多' },
        // component: () => import('@/views/About/Index.vue')
        redirect: '/home/more',
        children: [
          {
            path: 'Quotation',
            name: 'Quotation',
            meta: { title: '首页' },
            component: () => import('@/views/More/Quotation.vue')
          }
        ]
      }
    ]
  },
  {
    path: '/admin',
    name: 'Admin',
    meta: { title: '后台管理' },
    component: () => import('@/views/Admin/Layout/Index.vue'),
    redirect: '/admin/dashboard',
    children: [
      {
        path: 'dashboard',
        name: '控制台',
        meta: {
          title: '控制台',
          breadcrumb: ['后台管理', '控制台']
        },
        component: () => import('@/views/Admin/Dashboard/Index.vue')
      },
      {
        path: 'user',
        name: 'user',
        meta: {
          title: '用户管理',
          breadcrumb: ['后台管理', '用户管理']
        },
        redirect: '/user/list',
        children: [
          {
            path: 'list',
            name: 'userList',
            meta: {
              title: '用户列表',
              breadcrumb: ['后台管理', '用户管理', '用户列表']
            },
            component: () => import('@/views/admin/User/List.vue')
          }
        ]
      },
      {
        path: 'system',
        name: 'System',
        meta: {
          title: '系统管理',
          breadcrumb: ['后台管理', '系统管理']
        },
        // component: () => import('@/views/admin/enterprise/List.vue'),
        redirect: '/system/menu',
        children: [
          {
            path: 'menu',
            name: 'Menu',
            meta: {
              title: '菜单管理',
              breadcrumb: ['后台管理', '系统管理', '菜单管理']
            },
            component: () => import('@/views/Admin/System/Menu/Index.vue')
          },
          {
            path: 'website',
            name: 'Website',
            meta: {
              title: '网站信息',
              breadcrumb: ['后台管理', '系统管理', '网站信息']
            },
            component: () => import('@/views/Admin/System/Website/Information.vue')
          },
          {
            path: 'notice',
            name: 'notice',
            meta: {
              title: '通知公告',
              breadcrumb: ['后台管理', '系统管理', '通知公告']
            },
            component: () => import('@/views/Admin/System/Notice/Index.vue')
          },
          {
            path: 'blogroll',
            name: 'Blogroll',
            meta: {
              title: '友情链接',
              breadcrumb: ['后台管理', '系统管理', '友情链接']
            },
            component: () => import('@/views/Admin/System/Blogroll/Index.vue')
          }
        ]
      }
    ]
  },
  {
    // 404
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    meta: { title: '错误页面' },
    component: () => import('@/views/Layout/NotFound.vue')
  },
  {
    // 登录
    path: '/login',
    name: 'Login',
    meta: { title: '登录' },
    component: () => import('@/views/Login/Index.vue')
  }
]

// 重置路由
export const INDEX_ROUTE_NAME = Symbol()
export function resetRouter() {
  router.removeRoute(INDEX_ROUTE_NAME)
  const { routes: any } = useUserStore()
  routes.forEach((route: any) => {
    console.log('route ==>', route)
    const name = route.name
    if (name && router.hasRoute(name)) {
      router.removeRoute(name)
    }
  })
}

const router = createRouter({
  // history: createWebHistory(), // 不带 # 号
  history: createWebHashHistory(), // 带 # 号
  routes
})
/**
 * 配置进度条，不需要小圈圈
 */
NProgress.configure({ showSpinner: false })

const loginPath = PageEnum.LOGIN
const defaultPath = PageEnum.INDEX
// 免登录白名单
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
// 路由跳转前的监听操作
router.beforeEach(async (to, from, next) => {
  // 启动进度条
  NProgress.start()
  // 修改title
  document.title = to.meta.title + ' - 无锡九五装饰设计工程有限公司'
  const userStore = useUserStore()

  await userStore.getMenu()
  const routes = userStore.routes
  console.log('router ==========', router, to.path)
  if (whiteList.includes(to.path)) {
    // 在免登录白名单，直接进入
    next()
  } else if (userStore.token) {
    // 获取用户信息
    const hasGetUserInfo = Object.keys(userStore.userInfo).length !== 0
    if (hasGetUserInfo) {
      if (to.path === loginPath) {
        next({ path: defaultPath })
      } else {
        next()
      }
    } else {
      try {
        await userStore.getMenu()
        const routes = userStore.routes
        console.log('router ==========', router)
      } catch (err) {
        clearAuthInfo()
        next({ path: loginPath, query: { redirect: to.fullPath } })
      }
    }
  } else {
    console.log('没有token')
  }

  next()
  NProgress.done()
})

/**
 * 进度条完成
 */
router.afterEach(() => {
  NProgress.done()
})

export default router
